﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CE.InputOut;
using System.Net;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Request.Params["message"] != null && Request.Params["message"].ToString().ToLower() == "thankyou")
            {
                divRecording.Visible = false;
                divParagraph.Visible = false;
                divThankYou.Visible = true;
                divButton.Visible = false;
                Session["LastFileName"] = null;
            }

            if (Request.Params["file"] != null)
            {
                Response.Redirect("record-exist.aspx?file=" + Request.Params["file"].ToString());
            }

            if (Request["filename"] != null)
            {
                string _webUrl = string.Empty;
                string _filePath = GetFilePath(out _webUrl);
                string _guidString = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 8);
                string _fileName = "Voice_" + _guidString + "_" + DateTime.Now.ToString("_ddMMMyyyy_hhmmss_tt") + ".wav";

                string fileName = _filePath + _fileName;
                _webUrl = _webUrl + _fileName;

                using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
                {
                    byte[] bytes = new byte[8192];
                    int bytesRead;
                    while ((bytesRead = Request.InputStream.Read(bytes, 0, bytes.Length)) > 0)
                    {
                        fs.Write(bytes, 0, bytesRead);
                    }

                }

                Session["LastFileName"] = _webUrl;
                Session["StoreLastFileName"] = fileName;
            }

            if (Session["LastFileName"] != null)
            {
                hplDownload.NavigateUrl = Session["LastFileName"].ToString();
                hplDownload.Text = "Your last recorded file.";
                divButton.Visible = true;
                divRecording.Visible = false;
                divParagraph.Visible = false;
            }
        }
        catch (Exception Ex)
        {
            CreateExceptionLog(Ex, "Page_Load");
        }
    }

    private static void CreateExceptionLog(Exception Ex, string strLocation)
    {
        String[] _fileContent = new String[7];
        _fileContent[1] = "Source : " + Ex.Source;
        _fileContent[2] = "Date Time : " + DateTime.Now.ToString();
        _fileContent[3] = "Stack Trace :" + Ex.StackTrace.ToString();
        _fileContent[4] = "Target Site : " + Ex.TargetSite.ToString();
        _fileContent[5] = "Location : " + "MyMailManager - " + strLocation;
        _fileContent[6] = "Message : " + Ex.Message;

        WriteExceptionLog("Ex_", _fileContent);
    }

    private static void WriteExceptionLog(string strPrefixFileName, string[] strException)
    {
        try
        {
            CE.InputOut.MyIO _newFile = new CE.InputOut.MyIO();
            string _filePath = AppDomain.CurrentDomain.BaseDirectory + "Exception\\";
            if (_newFile.CheckDirectory(_filePath))
            {
                string _curMonth = DateTime.Now.Year.ToString("0000") + DateTime.Now.Month.ToString("00");

                if (!_newFile.CheckDirectory(_filePath + _curMonth))
                {
                    if (_newFile.CreateDirectory(_filePath, _curMonth))
                    {
                        _filePath += _curMonth + "\\";
                    }
                }
                else
                {
                    _filePath += _curMonth + "\\";
                }

                string _fileName = strPrefixFileName + _curMonth + DateTime.Now.Day.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("00") + ".txt";

                _newFile.WriteNewFile(_filePath, _fileName, strException);
                _newFile = null;
            }
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

    private string GetFilePath(out string webUrl)
    {
        string _filePath = Server.MapPath("~\\voice-recording\\upload\\");
        CE.InputOut.MyIO _myIO = new CE.InputOut.MyIO();
        webUrl = "~/voice-recording/upload/";
        //string _curYear = DateTime.Now.ToString("yyyy");
        //if (!_myIO.CheckDirectory(_filePath + _curYear))
        //{
        //    if (_myIO.CreateDirectory(_filePath, _curYear))
        //    {
        //        _filePath += _curYear + "\\";
        //        webUrl += _curYear + "/";
        //    }
        //}
        //else
        //{
        //    _filePath += _curYear + "\\";
        //    webUrl += _curYear + "/";
        //}

        //string _curMonth = DateTime.Now.ToString("MMMM");
        //if (!_myIO.CheckDirectory(_filePath + _curMonth))
        //{
        //    if (_myIO.CreateDirectory(_filePath, _curMonth))
        //    {
        //        _filePath += _curMonth + "\\";
        //        webUrl += _curMonth + "/";
        //    }
        //}
        //else
        //{
        //    _filePath += _curMonth + "\\";
        //    webUrl += _curMonth + "/";
        //}

        //string _todaydate = DateTime.Now.ToString("ddMMMMyyyy");
        //if (!_myIO.CheckDirectory(_filePath + _todaydate))
        //{
        //    if (_myIO.CreateDirectory(_filePath, _todaydate))
        //    {
        //        _filePath += _todaydate + "\\";
        //        webUrl += _todaydate + "/";
        //    }
        //}
        //else
        //{
        //    _filePath += _todaydate + "\\";
        //    webUrl += _todaydate + "/";
        //}



        //string _file = "RecordingFiles_" + _todaydate;
        //if (!_myIO.CheckDirectory(_filePath + _file))
        //{
        //    if (_myIO.CreateDirectory(_filePath, _file))
        //    {
        //        _filePath += _file + "\\";
        //        webUrl += _file + "/";
        //    }
        //}
        //else
        //{
        //    _filePath += _file + "\\";
        //    webUrl += _file + "/";
        //}

        string _file = "Temp";
        if (!_myIO.CheckDirectory(_filePath + _file))
        {
            if (_myIO.CreateDirectory(_filePath, _file))
            {
                _filePath += _file + "\\";
                webUrl += _file + "/";
            }
        }
        else
        {
            _filePath += _file + "\\";
            webUrl += _file + "/";
        }

        return _filePath;
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Session["StoreLastFileName"] != null)
        {
            Session["ConfirmLastFileName"] = Session["StoreLastFileName"];
        }

        Response.Redirect("default.aspx?message=thankyou");
        //this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Close", "window.close();", true);
    }

    protected void btnRecordNew_Click(object sender, EventArgs e)
    {
        divButton.Visible = false;
        divParagraph.Visible = true;
        divRecording.Visible = true;
    }

    protected void btnEmailTest_Click(object sender, EventArgs e)
    {
        //if (Page.IsValid)
        //{
        //    IPAddress[] ips;

        //    string hostname = txtEmail.Text.Trim().Split('@')[1];
        //    ips = Dns.GetHostAddresses(hostname);

        //    lblEmailTestResult.Text = string.Format("GetHostAddresses({0}) returns:", hostname);

        //    foreach (IPAddress ip in ips)
        //    {
        //        lblEmailTestResult.Text += string.Format("<br/>    {0}", ip);
        //    }
        //}
    }
}
